package com.wenkang.stu.config.security;

import com.wenkang.stu.config.security.filter.JwtValidationFilter;
import com.wenkang.stu.config.security.handler.DeniedHandler;
import com.wenkang.stu.config.security.handler.EntryPointHandler;
import com.wenkang.stu.pojo.SysRole;
import com.wenkang.stu.pojo.SysUser;
import com.wenkang.stu.service.SysRoleService;
import com.wenkang.stu.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityMetadataSource metadataSource;
    @Autowired
    private SecurityAccessDecisionManager accessDecisionManager;

    // 未登录处理
    @Autowired
    private EntryPointHandler entryPointHandler;

    // 权限不足处理
    @Autowired
    private DeniedHandler deniedHandler;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Override
    public void configure(WebSecurity web) {
        // 放行路径(无需登录)
        web.ignoring().antMatchers(
                "/login",
                "/logout",
                "/css/**",
                "/js/**",
                "/index.html",
                "favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/swagger-ui.html",
                "/v2/api-docs/**"
        );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(metadataSource);
                        o.setAccessDecisionManager(accessDecisionManager);
                        return o;
                    }
                })
                .and().exceptionHandling()
                .authenticationEntryPoint(entryPointHandler)
                .accessDeniedHandler(deniedHandler)
                .and()
                // todo 跨域允许一定要开！！！！！！！
                .cors()
                .and()
                .addFilterBefore(new JwtValidationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return s -> {
            SysUser user = userService.selectByUsername(s);
            List<SysRole> roles = roleService.selectByUserId(user.getId());
            user.setRoles(roles);
            return user;
        };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
